class Slide {
  constructor(element, range) {
    this.element = element; //目标DOM元素
    this.range = range || 20; //滑动距离，大于或者等于这个值时才算有效的滑动
    this.moving = false;
    this.startX = 0;
    this.startY = 0;
    this.endX = 0;
    this.endY = 0;
  }

  slideUp(callback) {
    this.slide("up", callback);
  }

  slideDown(callback) {
    this.slide("down", callback);
  }

  slideLeft(callback) {
    this.slide("left", callback);
  }

  slideRight(callback) {
    this.slide("right", callback);
  }

  slide(direction, callback) {
    this.element.addEventListener(
      "touchstart",
      (e) => this.touchstart(e),
      false
    );
    this.element.addEventListener("touchmove", (e) => this.touchmove(e), false);
    this.element.addEventListener(
      "touchend",
      (e) => this.touchend(direction, callback, e),
      false
    );
  }

  touchstart(e) {
    let touches = e.touches[0];
    let { clientX, clientY } = touches;
    [this.startX, this.startY] = [clientX, clientY];
    this.moving = false;
  }

  touchmove(e) {
    this.moving = true;
  }

  touchend(direction, callback, e) {
    if (!this.moving) {
      return;
    }
    let cb = (...args) => typeof callback === "function" && callback(...args);
    let touches = e.changedTouches[0];
    let { clientX, clientY } = touches;
    [this.endX, this.endY] = [clientX, clientY];
    let distanceX = this.startX - this.endX;
    let distanceY = this.startY - this.endY;
    let action =
      Math.abs(distanceX) >= Math.abs(distanceY) ? "left-right" : "up-down";
    if (action === "left-right") {
      if (distanceX < -this.range) {
        direction === "right" && cb();
      } else if (distanceX > this.range) {
        direction === "left" && cb();
      }
    } else if (action === "up-down") {
      if (distanceY < -this.range) {
        direction === "down" && cb();
      } else if (distanceY > this.range) {
        direction === "up" && cb();
      }
    }
  }
}

class bannerCard extends Slide {
  constructor(id, btn, bg, slideElement, options) {
    // 存储默认值
    super(slideElement); //类增强,增加滑动功能
    this.default = {
      classArray: [`two`, `three ${id}index`, `four`],
      leftSlider: false,
    };
    // options覆盖默认值
    Object.assign(this.default, options);

    this.bannerWrap = document.getElementById(id);
    this.lis = this.bannerWrap.getElementsByTagName("li");
    this.id = id;
    this.time = null;
    this.bg = bg;
    this.btn = btn;
    // 将类数组转化为数组（ES6用法）
    this.lisArray = Array.from(this.lis);
    if (bg == true) {
      this.default.classArray = ["two2", `three ${id}index`, `four2`];
    }
    //前面三个已经做了排序
    let newlist = [...this.lisArray];
    newlist.splice(1, 3);
    //  切割后,遍历剩余的数组.给样式标记索引
    for (let index = 0; index < newlist.length; index++) {
      this.default.classArray.push(`other`);
    }
    this.classlist = this.default.classArray;
    this.leftSlider = this.default.leftSlider;
    this.leftBtn = document.getElementById(btn.left);
    this.rightBtn = document.getElementById(btn.right);

    this.index = 0;
    this.init();
    this.listenMouse = this.listenMouse;
    this.result = this.result;
    this.time1 = null;
    this.time2 = null;
    this.time3 = null;
    this.slideElement = slideElement;
  }
  init() {
    // li的class进行初始化操作
    this.initLiClass();
    this.startTimer();
  }

  // 开始定时器
  startTimer() {
    this.timer();
  }

  // 清除定时器
  clearTimer() {
    clearInterval(this.time);
  }

  // li的class进行初始化操作
  initLiClass() {
    this.move(this.classlist);
  }

  // 定时器
  timer() {
    let self = this;
    if (self.leftSlider) {
      self.time = setInterval(self.leftMove.bind(this), 3000);
    } else {
      self.time = setInterval(self.rightMove.bind(this), 3000);
    }
  }

  // 运动函数
  move(list) {
    let self = this;
    self.lisArray.forEach((value, index) => {
      value.setAttribute("class", list[index]);
    });
  }

  // 向左运动
  leftMove() {
    let self = this;
    let popValue = self.classlist.pop();
    self.classlist.unshift(popValue);
    self.move(self.classlist);
    if (this.index == 0) {
      this.index = this.lisArray.length - 1;
    } else {
      this.index--;
    }
  }

  // 向右运动
  rightMove() {
    let self = this;
    let shiftValue = self.classlist.shift();
    self.classlist.push(shiftValue);
    self.move(self.classlist);
    if (this.index == this.lisArray.length - 1) {
      this.index = 0;
    } else {
      this.index++;
    }
  }
  // 鼠标点击左右按钮事件
  listenMouse(cb, first = true) {
    let self = this;
    if (first === true) {
      this.time3 = setInterval(() => {
        cb && cb(this.index);
      }, 3000);
    }
    // 左点击事件
    self.leftBtn.addEventListener("click", this.leftHandle.bind(this, cb));

    //右点击事件
    self.rightBtn.addEventListener("click", this.righthandle.bind(this, cb));
  }

  righthandle(cb) {
    this.clearAllTime();
    this.rightMove();

    cb && cb(this.index);
    this.time1 = setTimeout(() => {
      this.timer();
      this.time2 = setInterval(() => {
        cb && cb(this.index);
      }, 3000);
    }, 2000);
  }
  clearAllTime() {
    clearTimeout(this.time1);
    clearInterval(this.time);
    clearInterval(this.time2);
    clearInterval(this.time3);
  }
  leftHandle(cb) {
    this.clearAllTime();
    this.leftMove();
    cb && cb(this.index);
    this.time1 = setTimeout(() => {
      this.timer();
      this.time2 = setInterval(() => {
        cb && cb(this.index);
      }, 3000);
    }, 2000);
  }
  result() {
    //清除所有计时器.并且解绑当前轮播图按钮的事件
    this.clearAllTime();
    this.leftBtn.removeEventListener("click", this.leftHandle, false);
    this.rightBtn.removeEventListener("click", this.rightBtn, false);
    this.slideElement.removeEventListener("touchend", super.touchend, false);
    this.slideElement.removeEventListener("touchmove", super.touchmove, false);
    this.slideElement.removeEventListener(
      "touchstart",
      super.touchstart,
      false
    );
  }
  touch(cb) {
    const self = this;
    let slideElement = this.slideElement;
    var timeout = null;
    $(slideElement)
      .mousedown(function (e) {
        e.preventDefault();
        let startX = e.pageX;
        let startY = e.pageY;
        $(this).mousemove(function (e) {
          e.preventDefault();
          let moveEndX = e.pageX;
          let moveEndY = e.pageY;

          let X = moveEndX - startX;
          let Y = moveEndY - startY;
          clearTimeout(timeout);
          if (X > 0) {
            timeout = setTimeout(() => {
              console.log("left -> right");
              self.righthandle()
              cb && cb(self.index);
            }, 300);
          } else {
            timeout = setTimeout(() => {
              console.log("right -> left");
              self.leftHandle()
              cb && cb(self.index);
            }, 300);
          }
        });
      })
      .mouseup(function () {
        $(this).off("mousemove");
      });
    // super.slideLeft(() => {
    //   this.leftHandle(cb);
    //   cb && cb(self.index);
    // });
    // super.slideRight(() => {
    //   this.righthandle(cb);
    //   cb && cb(self.index);
    // });
  }
}
